<?php
/**
 * Created by PhpStorm.
 * User: HS032
 * Date: 2021/4/28
 * Time: 10:49
 */

namespace pay\forms\fontend\order;




use pay\libs\Msg;
use pay\libs\Tools;
use pay\modules\frontend\models\Order;
use pay\modules\frontend\models\OrderDetails;
use yii\base\Exception;
use yii\log\FileTarget;

class OrderForm extends \yii\base\Model
{
    public $form_data;
    public $pay_order_sn;

    public function rules()
    {
        return [
            [['form_data'], 'required'],
        ];
    }

    /**
     * @return array
     * @throws \yii\base\Exception
     */
    public function submit()
    {
        if (!$this->validate()) {
            throw new Exception('数据异常',10045);
        }
//        var_dump($this->form_data);die;
        $orderModel = new Order();
        $orderDetailsModel = new OrderDetails();
        $model = $orderModel->getInfo($this->form_data['payNo'],$this->form_data['appId']);
        $msgModel = new Msg();
        $transaction = \Yii::$app->db->beginTransaction();
        try{
            if ($model['pay_status'] == 3){
                throw new Exception('该订单已支付',99);
            }
            if (empty($model)){
                $this->pay_order_sn = $pay_order_sn = Tools::createSn();  // 支付单号
                $this->form_data['pay_order_sn'] = $pay_order_sn;
                if (!$oid = $orderModel->addOrder($this->form_data)){
                    if ($orderModel->hasErrors()){
                        $this->recordLogin('99','添加订单失败',json_encode($orderModel->getErrors()));
                        throw new Exception('添加订单失败',10056);
                    }else{
                        throw new Exception('添加订单失败',10056);
                    }
                }
                if (!$orderDetailsModel->addInfo($oid,$this->form_data)){
                    if ($orderDetailsModel->hasErrors()){
                        $this->recordLogin('99','添加订单详情失败',json_encode($orderDetailsModel->getErrors()));
                        throw new Exception('添加订单失败',10057);
                    }else{
                        throw new Exception('添加订单失败',10057);
                    }
                }
            }else{
                $this->form_data['pay_order_sn'] = $model['pay_order_sn'];
            }
            $transaction->commit();
            return ['code' => 0,'msg' => $this->form_data];
        }catch (Exception $e){
            $transaction->rollBack();
            $msgModel->insertMsg('99',json_encode($this->form_data),$e->getMessage());
            return ['code' => $e->getCode(),'msg' => $e->getMessage()];
        }





    }

    protected function recordLogin($code,$msg,$data)
    {
        $log = new FileTarget();
        $log->logFile = \Yii::$app->getRuntimePath() . '/wxPay/pay_' . date('Ymd') . '.log';
        $log->messages[] = [
            "[url:{$_SERVER['REQUEST_URI']}],[data:{$code},{$msg},{$data}]",
            1,
            'application',
            time(),
        ];
        $log->export();
    }






}